package com.salesmanager.web.admin.controller.app;


import com.salesmanager.core.business.app.model.AndroidChannel;
import com.salesmanager.core.business.app.service.AppChannelService;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.statistics.model.AppChannelCriteria;
import com.salesmanager.core.utils.MD5Util;
import com.salesmanager.web.admin.controller.AbstractController;
import com.salesmanager.web.admin.controller.ControllerConstants;
import com.salesmanager.web.admin.entity.catalog.AppChannelConfiguration;
import com.salesmanager.web.entity.app.AppChannelAttribute;
import com.salesmanager.web.entity.app.AppChannelEntity;
import com.salesmanager.web.model.paging.PaginationDataList;
import com.salesmanager.web.utils.ImageFilePathUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by Liutong on 2016/1/13.
 */

@Controller
public class AppChannelController extends AbstractController {

    @Autowired
    private AppChannelService appChannelService;

    @RequestMapping("/channel/appChannelList")//rtyu
    public String appChannelList(@ModelAttribute("channelAttribute") AppChannelAttribute channelAttribute, Model model, HttpServletRequest request, HttpServletResponse response) {
        super.setMenu(model, request, Arrays.asList("appPackage-manager", "android-channel"), "android-channel");
        AppChannelCriteria criteria = new AppChannelCriteria();
        //分页
        criteria.setMaxCount(channelAttribute.getPageSize());
        criteria.setStartIndex(channelAttribute.getOffset() - 1);
        //渠道编码
        if (!StringUtils.isBlank(channelAttribute.getChannelCode())) {
            criteria.setChannelCode(channelAttribute.getChannelCode());
        }
        //渠道名称
        if (!StringUtils.isBlank(channelAttribute.getChannelName())) {
            criteria.setChannelName(channelAttribute.getChannelName());
        }
        //ctrl + alt + v  补全返回值
        //ctrl + alt + l  格式化代码
        PaginationDataList<AndroidChannel> datas = appChannelService.getAppChannelList(criteria);
        PaginationDataList<AppChannelEntity> dataList = new PaginationDataList<AppChannelEntity>();
        List<AppChannelEntity> lists = new ArrayList<AppChannelEntity>();
        for (AndroidChannel data : datas.getData()) {
            AppChannelEntity appChannelEntity = new AppChannelEntity();
            appChannelEntity.setId(data.getId());
            appChannelEntity.setFileSize(data.getFileSize());
            appChannelEntity.setFileName(data.getFileName());
            appChannelEntity.setChannelCode(data.getChannelCode());
            appChannelEntity.setChannelName(data.getChannelName());
            appChannelEntity.setVersion(data.getVersion());
            String path = ImageFilePathUtils.buildChannelApkFilePath(data.getChannelCode(), data.getFileName(), request);
            appChannelEntity.setFilePath(path);
            lists.add(appChannelEntity);
        }
        dataList.setData(lists);
        dataList.setTotalCount(datas.getTotalCount());
        model.addAttribute("dataList", dataList);
        return ControllerConstants.Tiles.AppChannel.appChannelList;
    }

    @RequestMapping("/channel/appChannelPage")
    public String appChannelPage(Model model, HttpServletRequest request, HttpServletResponse response) {
        super.setMenu(model, request, Arrays.asList("appPackage-manager", "android-channel"), "android-channel");
        String channelId = request.getParameter("channelId");
        AppChannelConfiguration configuration = new AppChannelConfiguration();
        AndroidChannel androidChannel = null;
        if (!StringUtils.isBlank(channelId)) {
            androidChannel = appChannelService.getById(Long.parseLong(channelId));
            configuration.setAndroidChannel(androidChannel);
        } else {
            androidChannel = new AndroidChannel();
            configuration.setAndroidChannel(androidChannel);
        }
        model.addAttribute("configuration", configuration);
        model.addAttribute("channelId", channelId);
        return ControllerConstants.Tiles.AppChannel.appChannel;
    }

    @RequestMapping("/channel/saveChannel")
    public String saveChannel(@ModelAttribute("configuration") AppChannelConfiguration configuration, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException {
        super.setMenu(model, request, Arrays.asList("appPackage-manager", "android-channel"), "android-channel");
        AndroidChannel androidChannel = configuration.getAndroidChannel();
        if (androidChannel.getId() != null) {
            androidChannel = appChannelService.getById(androidChannel.getId());
            androidChannel.setChannelCode(configuration.getAndroidChannel().getChannelCode());
            androidChannel.setChannelName(configuration.getAndroidChannel().getChannelName());
            androidChannel.setInnerVersion(configuration.getAndroidChannel().getInnerVersion());
            androidChannel.setVersion(configuration.getAndroidChannel().getVersion());
            androidChannel.setVersionDesc(configuration.getAndroidChannel().getVersionDesc());
            androidChannel.setRequiredUpdate(configuration.getAndroidChannel().getRequiredUpdate());
        }
        if (configuration.getChannelFile() != null && !configuration.getChannelFile().isEmpty()) {
            MultipartFile file = configuration.getChannelFile();
            long size = file.getSize();
            androidChannel.setFileSize((int) size);
            String fileName = file.getOriginalFilename();
            androidChannel.setApkFileInputStream(configuration.getChannelFile().getInputStream());
            androidChannel.setFileName(fileName);
            String fileMD5 = MD5Util.getFileMD5(file.getInputStream());
            androidChannel.setFileMd5(fileMD5);
        }
        this.appChannelService.saveOrUpdate(androidChannel);
        return "redirect:/channel/appChannelList";
    }

    @RequestMapping("channel/deleteChannel")
    @ResponseBody
    public Map deleteChannel(Model model, HttpServletRequest request) {
        super.setMenu(model, request, Arrays.asList("appPackage-manager", "android-channel"), "android-channel");
        String channelId = request.getParameter("channelId");
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtils.isBlank(channelId)) {
            try {
                this.appChannelService.deleteById(Long.parseLong(channelId));
                map.put("key", 0);//success
                return map;
            } catch (NumberFormatException e) {
                map.put("key", 1);//失败
                return map;
            }
        } else {
            map.put("key", 1);//失败
            return map;
        }
    }
}
